<template>
  <div class="customer-analysis">
    <!-- Title section -->
    <div class="header-section">
      <h1 class="main-title">Customer Data Analysis</h1>
      <p class="sub-title">
        This dashboard page analyses specific information about customers, including their number city, age, gender,
        spending habits
        and more.
      </p>
    </div>

    <!-- Content section -->
    <div class="content-section">
      <!-- Filter section -->
      <div class="filter-section">
        <el-form :inline="true" :model="filterForm">
          <el-form-item>
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="to"
              start-placeholder="Start Date"
              end-placeholder="End Date"
              value-format="YYYY-MM-DD"
              style="width: 260px" />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="filterForm.category"
              placeholder="Product Category"
              clearable
              style="width: 200px">
              <el-option
                v-for="item in categories"
                :key="item"
                :label="item"
                :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button type="primary" @click="handleFilter">
                <el-icon>
                  <Search />
                </el-icon>
                Filter
              </el-button>
              <el-button @click="resetFilter">
                <el-icon>
                  <Refresh />
                </el-icon>
                Reset
              </el-button>
            </el-button-group>
          </el-form-item>
        </el-form>
      </div>

      <!-- Upper section -->
      <div class="upper-section">
        <el-row :gutter="20">
          <!-- Left cards -->
          <el-col :span="6">
            <div class="kpi-wrapper">
              <div class="kpi-section">
                <div v-for="(kpi, index) in kpiData" :key="index">
                  <el-card class="kpi-card" shadow="hover">
                    <div class="kpi-title">{{ kpi.title }}</div>
                    <div class="kpi-value">{{ kpi.value }}</div>
                    <div class="kpi-trends">
                      <div class="trend-item">
                        <div class="trend-label">Week-over-Week</div>
                        <div :class="['trend-value', kpi.weekOnWeek > 0 ? 'up' : 'down']">
                          <el-icon>
                            <CaretTop v-if="kpi.weekOnWeek > 0" />
                            <CaretBottom v-else />
                          </el-icon>
                          {{ Math.abs(kpi.weekOnWeek) }}%
                        </div>
                      </div>
                      <div class="trend-item">
                        <div class="trend-label">Day-over-Day</div>
                        <div :class="['trend-value', kpi.dayOnDay > 0 ? 'up' : 'down']">
                          <el-icon>
                            <CaretTop v-if="kpi.dayOnDay > 0" />
                            <CaretBottom v-else />
                          </el-icon>
                          {{ Math.abs(kpi.dayOnDay) }}%
                        </div>
                      </div>
                    </div>
                  </el-card>
                </div>
              </div>
            </div>
          </el-col>

          <!-- Right charts -->
          <el-col :span="9">
            <el-card class="chart-card" shadow="hover">
              <div class="chart-title">{{ upperCharts[0].title }}</div>
              <ECharts :options="upperCharts[0].options" height="350px" />
            </el-card>
          </el-col>

          <!-- Right charts2 -->
          <el-col :span="9">
            <el-card class="chart-card" shadow="hover">
              <div class="chart-title">
                {{ upperCharts[1].title }}
                <el-icon
                  class="chart-type-switch"
                  @click="toggleChartType(0)"
                  :title="getNextChartTypeTitle(currentChartType[0])">
                  <component :is="getChartTypeIcon(currentChartType[0])" />
                </el-icon>
              </div>
              <ECharts :options="getAgeDistributionChartOptions(currentChartType[0])" height="350px" />
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- Lower section -->
    <div class="lower-section">
      <el-row :gutter="20">
        <!-- Consumption per capita and profit per capita -->
        <el-col :span="8">
          <el-card class="chart-card" shadow="hover">
            <div class="chart-title">
              {{ lowerCharts[0].title }}
              <el-icon
                class="chart-type-switch"
                @click="toggleChartType(2)"
                :title="getNextChartTypeTitle(currentChartType[2])">
                <component :is="getChartTypeIcon(currentChartType[2])" />
              </el-icon>
            </div>
            <ECharts :options="getChartOptions(currentChartType[2], 2)" height="350px" />
          </el-card>
        </el-col>

        <!-- Customer City Distribution -->
        <el-col :span="8">
          <el-card class="chart-card" shadow="hover">
            <div class="chart-title">
              {{ lowerCharts[1].title }}
              <el-icon
                class="chart-type-switch"
                @click="togglePieChartType"
                :title="getNextPieTypeTitle(currentPieChartType)">
                <component :is="getChartTypeIcon(currentPieChartType)" />
              </el-icon>
            </div>
            <ECharts :options="getPieChartOptions(currentPieChartType)" height="350px" />
          </el-card>
        </el-col>

        <!-- Customer consumption time preference -->
        <el-col :span="8">
          <el-card class="chart-card" shadow="hover">
            <div class="chart-title">
              {{ lowerCharts[2].title }}
              <el-icon
                class="chart-type-switch"
                @click="toggleChartType(3)"
                :title="getNextChartTypeTitle(currentChartType[3])">
                <component :is="getChartTypeIcon(currentChartType[3])" />
              </el-icon>
            </div>
            <ECharts :options="getChartOptions(currentChartType[3], 3)" height="350px" />
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { CaretTop, CaretBottom, Search, Refresh, TrendCharts, DataLine, Histogram } from '@element-plus/icons-vue'
import ECharts from '@/components/ECharts.vue'
import { getFilterOptions, getCustomerAnalysis } from '@/api/analysis'
import { ElMessage } from 'element-plus'

// 筛选表单数据
const filterForm = reactive({
  dateRange: [
    '2023-01-01',  // 默认开始日期
    '2023-12-31'   // 默认结束日期
  ],
  category: ''
})

// 产品类别选项
const categories = ref([])

// 图表类型状态
const chartTypes = ['bar', 'line', 'area']
const currentChartType = ref(['bar', 'pie', 'bar', 'bar']) // 每个图表的初始类型
const currentPieChartType = ref('pie') // 饼图类型状态

// 获取下一个图表类型的提示文字
const getNextChartTypeTitle = (currentType) => {
  switch (currentType) {
    case 'line': return '切换为面积图'
    case 'area': return '切换为柱状图'
    case 'bar': return '切换为折线图'
    default: return '切换图表类型'
  }
}

// 获取当前图表类型的图标
const getChartTypeIcon = (type) => {
  switch (type) {
    case 'bar':
    case 'ring':
      return TrendCharts
    case 'line':
    case 'funnel':
      return DataLine
    case 'area':
    case 'pie':
      return Histogram
    default:
      return TrendCharts
  }
}

// 切换图表类型
const toggleChartType = (index) => {
  const currentIndex = chartTypes.indexOf(currentChartType.value[index])
  const nextIndex = (currentIndex + 1) % chartTypes.length
  currentChartType.value[index] = chartTypes[nextIndex]
}

// 获取下一个饼图类型的提示文字
const getNextPieTypeTitle = (currentType) => {
  switch (currentType) {
    case 'pie': return '切换为环形图'
    case 'ring': return '切换为漏斗图'
    case 'funnel': return '切换为饼图'
    default: return '切换图表类型'
  }
}

// 切换饼图类型
const togglePieChartType = () => {
  currentPieChartType.value = currentPieChartType.value === 'pie' ? 'ring' : currentPieChartType.value === 'ring' ? 'funnel' : 'pie'
}

// 获取图表选项
const getAgeDistributionChartOptions = (type) => {
  const options = {
    ...upperCharts.value[1].options,
    series: [
      {
        ...upperCharts.value[1].options.series[0],
        type: type === 'area' ? 'line' : type
      }
    ]
  }
  if (type === 'area') {
    options.series[0].areaStyle = {
      color: {
        type: 'linear',
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        colorStops: [{
          offset: 0,
          color: 'rgba(103, 194, 58, 0.6)'
        }, {
          offset: 1,
          color: 'rgba(103, 194, 58, 0)'
        }]
      }
    }
  }
  return options
}

// 获取消费和利润图表选项
const getConsumptionChartOptions = (type) => {
  const options = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['Price', 'Profit']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.value.trend.months
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: value => formatKNumber(value)
      }
    },
    series: [
      {
        name: 'Price',
        type: type === 'area' ? 'line' : type,
        data: chartData.value.trend.avgConsumption,
        areaStyle: type === 'area' ? {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(64, 158, 255, 0.6)'
            }, {
              offset: 1,
              color: 'rgba(64, 158, 255, 0)'
            }]
          }
        } : null
      },
      {
        name: 'Profit',
        type: type === 'area' ? 'line' : type,
        data: chartData.value.trend.avgProfit,
        areaStyle: type === 'area' ? {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(103, 194, 58, 0.6)'
            }, {
              offset: 1,
              color: 'rgba(103, 194, 58, 0)'
            }]
          }
        } : null
      }
    ]
  }
  return options
}

// 获取消费时间偏好图表选项
const getTimePreferenceChartOptions = (type) => {
  const options = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['Customer Count']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.value.distribution.weekday.map(item => item.weekday)
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: value => formatKNumber(value)
      }
    },
    series: [
      {
        name: 'Customer Count',
        type: type === 'area' ? 'line' : type,
        data: chartData.value.distribution.weekday.map(item => item.count),
        areaStyle: type === 'area' ? {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(103, 194, 58, 0.6)'
            }, {
              offset: 1,
              color: 'rgba(103, 194, 58, 0)'
            }]
          }
        } : null
      }
    ]
  }
  return options
}

// 更新 getChartOptions 函数
const getChartOptions = (type, index) => {
  switch (index) {
    case 2: // Consumption per capita and profit per capita
      return getConsumptionChartOptions(type)
    case 3: // Customer consumption time preference
      return getTimePreferenceChartOptions(type)
    default:
      return {}
  }
}

// 获取饼图选项
const getPieChartOptions = (type) => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: params => `${params.name}<br/>count: ${formatNumber(params.value)}<br/>percent: ${params.percent}%`
    },
    series: [
      {
        type: type === 'ring' ? 'pie' : type,
        radius: type === 'ring' ? ['40%', '70%'] : '70%',
        data: chartData.value.distribution.city.map(item => ({
          name: item.name,
          value: item.value
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: type === 'pie' || type === 'ring' ? true : false,
          formatter: '{b}: {d}%'
        }
      }
    ]
  }
}

// 获取筛选选项数据
const loadFilterOptions = async () => {
  try {
    const options = await getFilterOptions()
    categories.value = options.categories
  } catch (error) {
    ElMessage.error('Failed to load filter options, please refresh the page')
  }
}

// 图表数据
const chartData = ref({
  kpiData: {
    totalCustomers: 0,
    weekOnWeek: 0,
    dayOnDay: 0,
    newCustomers: 0,
    newWeekOnWeek: 0,
    newDayOnDay: 0
  },
  distribution: {
    gender: [],
    age: [],
    city: [],
    weekday: [],
    consumption: []
  },
  trend: {
    months: [],
    avgConsumption: [],
    avgProfit: []
  },
  upperData: {
    productTrend: {
      months: [],
      volumes: []
    }
  }
})

// 获取分析数据
const fetchData = async () => {
  try {
    const data = await getCustomerAnalysis(filterForm)
    if (data) {
      chartData.value = data
    }
  } catch (error) {
    ElMessage.error('Failed to fetch analysis data, please try again')
  }
}

// 处理筛选
const handleFilter = async () => {
  await fetchData()
}

// 重置筛选
const resetFilter = () => {
  filterForm.dateRange = []
  filterForm.category = ''
  fetchData()
}

onMounted(() => {
  loadFilterOptions()
  fetchData()
})

// KPI数据
const kpiData = computed(() => [
  {
    title: 'Cumulative number of customers',
    value: formatNumber(chartData.value.kpiData.totalCustomers),
    weekOnWeek: chartData.value.kpiData.weekOnWeek.toFixed(2),
    dayOnDay: chartData.value.kpiData.dayOnDay.toFixed(2)
  },
  {
    title: 'Number of new customers',
    value: formatNumber(chartData.value.kpiData.newCustomers),
    weekOnWeek: chartData.value.kpiData.newWeekOnWeek.toFixed(2),
    dayOnDay: chartData.value.kpiData.newDayOnDay.toFixed(2)
  }
])

// 上部分图表配置
const upperCharts = computed(() => [
  {
    title: 'Gender Distribution',
    options: {
      tooltip: {
        trigger: 'item',
        formatter: params => {
          return `${params.name}<br/>count: ${formatNumber(params.value)}<br/>percent: ${params.percent}%`
        }
      },
      series: [
        {
          type: 'pie',
          radius: '50%',
          data: chartData.value.distribution?.gender?.map(item => ({
            name: item.name,
            value: item.value
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            formatter: '{b}: {d}%'
          }
        }
      ]
    }
  },
  {
    title: 'Age Distribution',
    options: {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: params => `${params[0].name}<br/>${params[0].seriesName}: ${formatNumber(params[0].value)}`
      },
      legend: {
        data: ['Customer Count']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: chartData.value.distribution?.age?.map(item => item.name)
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: value => formatKNumber(value)
        }
      },
      series: [
        {
          name: 'Customer Count',
          type: 'bar',
          data: chartData.value.distribution?.age?.map(item => ({
            value: item.value,
          }))
        }
      ]
    }
  },
])

// 下部分图表配置
const lowerCharts = computed(() => [
  {
    title: 'Consumption per capita and profit per capita',
    options: {
      tooltip: {
        trigger: 'axis',
        formatter: params => {
          return params.map(param => {
            return `${param.name}<br/>${param.seriesName}: $${formatNumber(param.value)}`
          }).join('<br/>')
        }
      },
      legend: {
        data: ['Average Consumption', 'Average Profit']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: chartData.value.trend.months,
        axisLabel: {
          formatter: value => value.toLowerCase()
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: value => `$${formatKNumber(value)}`
        }
      },
      series: [
        {
          name: 'Average Consumption',
          type: 'line',
          data: chartData.value.trend.avgConsumption.map(value => ({
            value
          })),
          smooth: true
        },
        {
          name: 'Average Profit',
          type: 'line',
          data: chartData.value.trend.avgProfit.map(value => ({
            value,
          })),
          smooth: true
        }
      ]
    }
  },
  {
    title: 'Customer City Distribution',
    options: {
      tooltip: {
        trigger: 'item',
        formatter: params => `${params.name}<br/>count: ${formatNumber(params.value)}<br/>percent: ${params.percent}%`
      },
      series: [
        {
          type: 'pie',
          radius: '50%',
          data: chartData.value.distribution.city.map(item => ({
            name: item.name,
            value: item.value
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            formatter: '{b}: {d}%'
          }
        }
      ]
    },
  },
  {
    title: 'Customer consumption time preference',
    options: {
      tooltip: {
        trigger: 'axis',
        formatter: params => `${params[0].name}<br/>${params[0].seriesName}: ${formatNumber(params[0].value)}`
      },
      legend: {
        data: ['Customer Count']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: chartData.value.distribution.weekday.map(item => item.weekday)
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: value => formatKNumber(value)
        }
      },
      series: [
        {
          name: 'Customer Count',
          type: 'bar',
          data: chartData.value.distribution.weekday.map(item => ({
            value: item.count,
          }))
        }
      ]
    }
  },
])

// 格式化数字（完整显示）
const formatNumber = (value) => {
  if (!value) return '0'
  return new Intl.NumberFormat('zh-CN').format(value)
}

// 格式化数字（K/M/B）
const formatKNumber = (value) => {
  if (!value) return '0'
  if (value >= 1000000) {
    return (value / 1000000).toFixed(1) + 'M'
  }
  if (value >= 1000) {
    return (value / 1000).toFixed(1) + 'K'
  }
  return value.toString()
}

// 格式化数字（K/M/B）
const formatKNumber2 = (value) => {
  if (!value) return '0'
  if (value >= 1000) {
    return (value / 1000).toFixed(1) + 'K'
  }
  return value.toString()
}
</script>

<style scoped>
.customer-analysis {
  width: calc(100vw - 400px);
  height: 100%;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.header-section {
  padding: 24px;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
}

.main-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2f3d;
  margin-bottom: 8px;
}

.sub-title {
  font-size: 14px;
  color: #5e6d82;
  margin: 0;
}

.content-section {
  padding: 24px;
}

.filter-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.filter-section :deep(.el-form--inline) {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-section :deep(.el-form-item) {
  margin-right: -6px;
  margin-bottom: 0;
}

.filter-section :deep(.el-button-group) {
  display: flex;
  gap: 8px;
}

.filter-section :deep(.el-button) {
  display: flex;
  align-items: center;
  gap: 4px;
}

.upper-section,
.lower-section {
  margin-bottom: 24px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  color: #303133;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
}

.chart-type-switch {
  cursor: pointer;
  font-size: 18px;
  color: #909399;
}

.chart-type-switch:hover {
  color: #409EFF;
  background-color: #ecf5ff;
}

:deep(.el-card) {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

:deep(.el-card:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-card__body) {
  padding: 0;
}

.kpi-wrapper {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
}

.kpi-section {
  margin-bottom: 0;
}

.kpi-section>div:not(:last-child) {
  margin-bottom: 16px;
}

.kpi-card {
  padding: 0 16px;
  background-color: #F8FAFC;
  border: 1px solid #E4E7ED;
  height: 160px;
}

.kpi-card:hover {
  background-color: #F2F6FC;
  border-color: #DCDFE6;
}

.kpi-title {
  color: #409EFF;
  font-size: 14px;
  padding-top: 16px;
  margin-bottom: 8px;
}

.kpi-value {
  font-size: 24px;
  margin-bottom: 16px;
}

.kpi-trends {
  padding-bottom: 8px;
  gap: 8px;
}

.trend-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.trend-label {
  width: 97px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 14px;
  color: #909399;
}

.trend-value {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

.trend-value.up {
  color: #f56c6c;
}

.trend-value.down {
  color: #67c23a;
}
</style>